<template>
  <div class="dialog-container">
    <el-row :gutter="10" class="mb8" v-if="!props.onlyShow">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['dispatch:schedulingPlanTimetable:add']">增加部位</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="moreAdd"
          v-hasPermi="['dispatch:schedulingPlanTimetable:add']">批量增加部位</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['dispatch:schedulingPlanTimetable:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dispatch:schedulingPlanTimetable:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
              v-hasPermi="['dispatch:schedulingPlanTimetable:import']">导入</el-button>
      </el-col>
    </el-row>
    <el-table :data="planTimeDatas" max-height="600" @selection-change="handleSelectionChange">
      <el-table-column fixed  type="selection" width="55" align="center" v-if="!props.onlyShow" />
      <el-table-column fixed  label="部位号" align="center" prop="place" />
      <el-table-column fixed  label="类型" align="center" prop="type" v-if="!props.onlyShow">
        <template #default="scope">
          <span>{{ scope.row.type == 1 ? '固定' : '灵活' }}</span>
        </template>
      </el-table-column>
      <template v-for="column_index in planTimeHeader">
        <el-table-column :label="`时间${column_index}`" align="center">
          <template #default="scope">
            <span>{{ scope.row.timetableList[column_index - 1] ? scope.row.timetableList[column_index - 1].planTime : ''
            }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="`开往方向${column_index}`" width="200" align="center">
          <template #default="scope">
            <span v-if="scope.row.timetableList[column_index - 1]">{{ scope.row.timetableList[column_index - 1].routeName
            }}
              {{ scope.row.timetableList[column_index - 1].direction == 1 ? '上行' : '下行' }}>{{
                scope.row.timetableList[column_index -
                  1].endStation
              }}</span>
          </template>
        </el-table-column>
      </template>

    </el-table>
    <el-dialog class="add_dialog" :title="title" v-model="open" width="600px" append-to-body>
      <template v-if="op == 'sigle'">
        <el-row style="margin-bottom: 20px;">
          <el-col :span="6"><el-button type="primary" plain icon="Plus" @click="add">增加时刻</el-button></el-col>
        </el-row>
        <el-form ref="schedulingPlanTimetable" :model="form" label-width="80px" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="部位号" prop="place">
                <el-input v-model="form.place" :disabled="title == '添加' ? true : false" placeholder="请输入部位号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部位类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择">
                  <el-option v-for="dict in types" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-for="(item, index) in form.timetableList" :key="index">
            <el-col :span="8">
              <el-form-item label="时间" :prop="'timetableList.' + index + '.planTime'" :rules="rules.planTime">
                <el-time-picker v-model="item.planTime" format="HH:mm" value-format="HH:mm" @change="changeTimer" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="方向" :prop="'timetableList.' + index + '.routeAndDirection'" :rules="rules.planTime">
                <el-select v-model="item.routeAndDirection" placeholder="请选择">
                  <el-option v-for="dict in selectList" :key="dict.routeId + '-' + dict.direction"
                    :label="dict.routeName + ' ' + (dict.direction == 1 ? '上行' : '下行') + '>' + dict.endStation"
                    :value="dict.routeId + '_' + dict.direction"></el-option>
                </el-select>
                <el-icon v-if="index>0" @click="del(index)">
                  <Close />
                </el-icon>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </template>
      <template v-else>
        <el-form ref="schedulingPlanTimetable" :model="moreForm" label-width="80px">

          <el-row>
            <el-col :span="24">
              <el-form-item label-width="140px" label="当日排班生成方式" prop="timetables"
                :rules="[{ required: true, message: '当日排班生成方式不能为空', trigger: 'blur' },]">
                <el-input rows="6" v-model="moreForm.timetables" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label-width="140px" label="说明">
                <div style="font-size: 12px;">
                  每一行一个部分时刻，每个时刻之间用#号分割，时刻由时间和上下行组成以逗号(,)分割。<br />
                  例如以下表示2个部位号的时刻：<br />
                  6:35,2#7:38,1#8:41,2#9:44,1#10:47,2#11:50,1#12:53,2<br />
                  6:44,2#7:47,1#8:50,2#9:53,1#10:56,2#11:59,1#14:05,2
                </div>

              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" action="#" :http-request="httpRequest"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag :data="upload.form">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
        

            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getListByPlanId, getListByPlace, schedulingPlanTime, getSelectListByPlace, addSchedulingPlanTime, delSchedulingPlanTime, batchAddSchedulingPlanTime } from "@/api/dispatch/schedulingPlan";
const { proxy } = getCurrentInstance();
import { getToken } from "@/utils/auth";
import { ref } from "vue";
const props = defineProps({
  // 当前的值
  planId: [Number, String],
  onlyShow:{
    type: Boolean,
    default: false
  }
});
const op = ref('sigle');
const buttonLoading = ref(false);
const ids = ref([]);
const places = ref([]);
const selectList = ref([]);
const multiple = ref(true);
const loading = ref(true);
const single = ref(true);
const planTimeDatas = ref([]);
const planTimeHeader = ref(0);
const title = ref("");
const open = ref(false);
const form = ref({
    "planId": props.planId,
    "place": null,
    "type": null,
    "deptId": null,
    "timetableList": [
    {"id":null,"routeId":null,"direction":null,"endStation":null,"planTime":"","routeAndDirection":null}
    ]
  })
const moreForm = ref({
  planId: null,
  timetables: null,
})
const types = ref([{ "label": "固定", "value": 1 }, { "label": "灵活", "value": 2 }]);
const rules = ref({
  place: [
    { required: true, message: "部位号不能为空", trigger: "blur" }
  ],
  type: [
    { required: true, message: "请选择部位类型", trigger: "change" }
  ],
  planTime: [
    { required: true, message: "请选择时间", trigger: "change" }
  ],
  direction: [
    { required: true, message: "请选择方向", trigger: "change" }
  ]
})

// 获取计划详情
function getPlanDeatil(id) {
  getListByPlanId(id).then(res => {
    if (res.data.length) {
      planTimeDatas.value = res.data
      let nums = 0;
      res.data.forEach(element => {
        let length = element.timetableList.length
        nums =  length > nums ? length : nums;
      });
      planTimeHeader.value = nums
    } else {
      planTimeDatas.value = []
      planTimeHeader.value = 0
    }
  })
}

function getDirectSelect(id) {
  getSelectListByPlace(id).then(res => {
    if (res.data.length) {
      selectList.value = res.data
    } else {
      selectList.value = []
    }
  })
}

watch(() => props.planId, (v) => {
  console.log('props.pid', v)
  getPlanDeatil(v)
  getDirectSelect(v)
}, { immediate: true });

// 多选框选中数据
function handleSelectionChange(selection) {
  places.value = selection.map(item => item.place);
  let tempIds = [];
  selection.map(item => {
    item.timetableList.map(vo=>{
      tempIds.push(vo.id)
    })
  });
  ids.value = Array.from(new Set(tempIds))
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const changeTimer = (val) => {
  console.log(val);
}
// 表单重置
function reset() {
  form.value = {
    "planId": props.planId,
    "place": null,
    "type": 1,
    "deptId": null,
    "timetableList": [
    {"id":null,"routeId":null,"direction":null,"endStation":null,"planTime":"","routeAndDirection":null}
    ]
  };
  proxy.resetForm("schedulingPlanTimetable");
}

//下一个部位号
function addPlaceNoShow(){
  if(planTimeDatas.value.length>0){
    form.value.place = planTimeDatas.value[planTimeDatas.value.length-1].place + 1
  }else{
    form.value.place = 1
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  addPlaceNoShow()
  open.value = true;
  op.value = 'sigle'
  title.value = "添加";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  op.value = 'sigle'
  reset();
  const _id = row.id || places.value
  getListByPlace(props.planId, _id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "编辑";
  });
}

function moreAdd() {
  op.value = 'more'
  open.value = true;
  title.value = "批量添加";
  moreForm.value.planId = props.planId
}

function add() {
  let obj = {
    "id": null,
    "routeId": null,
    "direction": null,
    "endStation": null,
    "planTime": '',
    "routeAndDirection": null
  }
  form.value.timetableList.push(obj)
}
function del(e) {
  console.log(e, form.value.timetableList)
  form.value.timetableList.splice(e, 1);
  // delete form.value.timetableList[e]
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["schedulingPlanTimetable"].validate(valid => {
    console.log(valid)
    if (valid) {
      buttonLoading.value = true;

      if (op.value == 'sigle') {
        form.value.timetableList.forEach((element, index) => {
          let info = element.routeAndDirection.split('_')
          form.value.timetableList[index].routeId = info[0]
          form.value.timetableList[index].direction = info[1]
        });
        if (form.value.place) {
          schedulingPlanTime(form.value).then(response => {
            proxy.$modal.msgSuccess("操作成功");
            open.value = false;
            getPlanDeatil(props.planId);
          }).finally(() => {
            buttonLoading.value = false;
          });
        } else {
          addSchedulingPlanTime(form.value).then(response => {
            proxy.$modal.msgSuccess("操作成功");
            open.value = false;
            getPlanDeatil(props.planId);
          }).finally(() => {
            buttonLoading.value = false;
          });
        }

      } else {
        batchAddSchedulingPlanTime(moreForm.value).then(response => {
          proxy.$modal.msgSuccess("操作成功");
          open.value = false;
          getPlanDeatil(props.planId);
        }).finally(() => {
          buttonLoading.value = false;
        });
      }

    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除排班计划编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delSchedulingPlanTime(_ids);
  }).then(() => {
    loading.value = true;
    getPlanDeatil(props.planId);
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  form: {
    planId: undefined,
  },
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url:  "dispatch/schedulingPlanTimetable/import/data"
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = "导入";
  upload.form.planId = props.planId
  upload.open = true;
};

/** 下载模板操作 */
function importTemplate() {
  proxy.download("dispatch/schedulingPlanTimetable/import/template", {
  }, `schedulingPlanTime_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getPlanDeatil(props.planId)
};

function httpRequest(data) {
  // 封装FormData对象
  data.data[data.filename] = data.file
  upload.open = false;
  upload.isUploading = false;
  proxy.importFile(upload.url, data.data).then(res => {
    console.log('import result', res)
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + res.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getPlanDeatil(props.planId)
  }).catch(err => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + err + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getPlanDeatil(props.planId)
  })
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

</script>

<style>
.add_dialog {
  max-height: 80%;
  overflow-y: auto;
}
</style>
